//
//  QRCodeView.m
//  SinaWebo
//
//  Created by wwj on 16/5/6.
//  Copyright © 2016年 亦心. All rights reserved.
//

#import "QRCodeView.h"
#import "CALayer+PauseAimate.h"
#import "MyCardViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface QRCodeView ()<AVCaptureMetadataOutputObjectsDelegate>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *qrLC;
@property (weak, nonatomic) IBOutlet UIView *contentView;
@property (weak, nonatomic) IBOutlet UIImageView *scanLineImg;

@property (strong, nonatomic) AVCaptureSession *session;
@property (weak, nonatomic) CALayer *drawLayer;
@property (weak, nonatomic) AVCaptureVideoPreviewLayer *vlayer;
@property (strong, nonatomic) CADisplayLink *link;

@property (copy, nonatomic) TypeBlock block;
@end

@implementation QRCodeView

+ (instancetype)qrCodeView{
    return [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:nil options:nil].lastObject;
}

- (void)awakeFromNib{
    self.qrLC.constant = -self.contentView.height;
    [self.contentView layoutIfNeeded];
    [self startAnimation];
    [self addTimer];
}


- (void)addTimer{
    self.link = [CADisplayLink displayLinkWithTarget:self selector:@selector(startAnimation)];
    [self.link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}

- (void)removeTimer{
    [self.link invalidate];
    self.link = nil;
}

- (void)startAnimation{
    self.link.paused = YES;
    [UIView animateWithDuration:2 animations:^{
        self.qrLC.constant = self.contentView.height;
        [self.contentView layoutIfNeeded];
    }completion:^(BOOL finished) {
        self.qrLC.constant = -self.contentView.height;
        self.link.paused = FALSE;
    }];
}

- (void)startScanWithBlock:(TypeBlock)block{
    self.block = block;
    AVCaptureSession *session = [[AVCaptureSession alloc] init];
    self.session = session;
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    [session addInput:input];
    
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    [session addOutput:output];
    
    [output setMetadataObjectTypes:output.availableMetadataObjectTypes];
    
    AVCaptureVideoPreviewLayer *vlayer = [AVCaptureVideoPreviewLayer layerWithSession:session];
    vlayer.frame = self.bounds;
    [self.layer insertSublayer:vlayer atIndex:0];
    self.vlayer = vlayer;
    
    CALayer *drawLayer = [[CALayer alloc] init];
    drawLayer.frame = self.bounds;
    [vlayer addSublayer:drawLayer];
    self.drawLayer = drawLayer;
    
    [session startRunning];
}


- (void)scanImageWithPhotoImage:(UIImage *)photoImage{
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy:CIDetectorAccuracyLow}];
    CIImage *ciImage = [CIImage imageWithData:UIImagePNGRepresentation(photoImage)];
    CIQRCodeFeature *feature = (CIQRCodeFeature *)([detector featuresInImage:ciImage].firstObject);
    if (self.block) {
        self.block(feature.messageString);
    }
}

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    [self.drawLayer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)];
    for (AVMetadataMachineReadableCodeObject *obj in metadataObjects) {
        AVMetadataMachineReadableCodeObject *metaData = (AVMetadataMachineReadableCodeObject *)[self.vlayer transformedMetadataObjectForMetadataObject:obj];
        [self drawLayer:metaData];
    }
    
    NSString *typeStr = [metadataObjects.lastObject stringValue];
    if (typeStr) {
        [self.session stopRunning];
        [self removeTimer];
//        [self.scanLineImg.layer pauseAnimate];
        if (self.block) {
            self.block(typeStr);
        }
    }

}

- (void)drawLayer:(AVMetadataMachineReadableCodeObject *)metaData{
    CAShapeLayer *sLayer = [[CAShapeLayer alloc] init];
    sLayer.lineWidth = 2;
    sLayer.strokeColor = [UIColor greenColor].CGColor;
    sLayer.fillColor = [UIColor clearColor].CGColor;
    sLayer.path = [self drawPath:metaData.corners];
    [self.drawLayer addSublayer:sLayer];
}

- (CGPathRef)drawPath:(NSArray *)pArray{
    UIBezierPath *path = [[UIBezierPath alloc] init];
    CGPoint point = CGPointZero;
    CFDictionaryRef dict = (__bridge CFDictionaryRef)(pArray[0]);
    CGPointMakeWithDictionaryRepresentation(dict, &point);
    [path moveToPoint:point];
    for (int index = 1; index < pArray.count; index++) {
        CGPointMakeWithDictionaryRepresentation((__bridge CFDictionaryRef)pArray[index], &point);
        [path addLineToPoint:point];
    }
    [path closePath];
    return path.CGPath;
}

- (IBAction)onClickMyCard{
    UITabBarController *tabBarVC = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *selectVC = tabBarVC.selectedViewController;
    UINavigationController *navigationVC = (UINavigationController *)selectVC;
    [navigationVC pushViewController:[[MyCardViewController alloc] init] animated:YES];
}

@end
